<?php require_once(dirname(__FILE__) . '/../include/config.inc.php');
require_once "function.php";

/*
进度：
0 已经撤单
1 报修成功
2 客服已经联系
3 系统已经派单
4 工程师接单
5 维修完成
6 已经评价
*/
$jindu = empty($jindu) ? '' : htmlspecialchars($jindu); //进度状态
$jindu = intval($jindu);
$uid = $_SESSION['id'];
$userInfo = "";
$this_openid = $_SESSION['openid'];

if (isset($uid)) {
    //有session 从数据库中读取用户名信息
    //$openid_str=$_SESSION['openid'];
    $sql = "SELECT u.*,g.groupname  as groupname  FROM `#@__user` as u 
				   left join `#@__usergroup` as g  on u.level=g.id  
				   WHERE u.id='$uid' ";
    $row_u = $dosql->GetOne($sql);
    if (is_array($row_u) && isset($row_u['id'])) {
        // 返回用户 id
        $id = $row['id'];
        $_SESSION['id'] = $id;
        $userInfo = $row_u;
        $level = intval($row_u['level']);
        $isadmin = $row_u['isadmin'];

    }
}

if ($isadmin == 0) {
    echo "<script>alert('您没有派单权限！')</script>";
    exit();
}


$orderid = empty($orderid) ? "" : intval($orderid);
if (isset($orderid)) {

    // 拉取用户信息
    $row = $dosql->GetOne("SELECT o.* FROM `#@__order` as o  WHERE o.id='$orderid'");
    if (is_array($row) && isset($row['id'])) {
        // 返回工单数据
        /*
        进度：
        0 已经撤单
        1 报修成功
        2 客服已经联系
        3 系统已经派单
        4 工程师接单
        5 维修完成
        6 已经评价
        */

        $jindu2 = $row['jindu'];
        $orderidname = date('Ymd', time()) . "-" . $id;
        $u_openid = $row['openid'];
        $guzhang = ClearHtml($row['content']);
        $guzhang = str_replace(PHP_EOL, '', $guzhang);
        $apply_device=$row['apply_device'];
        $guzhang = $row['content'];
        $truename = $row['truename'];
        $school = $row['school'];
        $mobile = $row['mobile'];
        $address = $row['address'] . "-" . $row['school'];
        $remark2 = $row['content'];


        //故障图片
        $pic_lists = "";
        $previewImage_url = array();
        $picurl_arr = explode(',', $row['picfiles']);
        array_pop($picurl_arr);
        for ($i = 0; $i < count($picurl_arr); $i++) {
            $previewImage_url[] = $picurl_arr[$i];
            $pic_lists .= '<li class="weui-uploader__file" style="background-image:url(' . $picurl_arr[$i] . ')"><img src="' . $picurl_arr[$i] . '" width="0"/></li>';
        }
    } else {
        echo "<script>alert('任务不存在或者已经删除！')</script>";
        exit();
    }
}
?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>反馈信息-技术支持系统</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="description" content="技术支持系统">
        <link rel="stylesheet" href="lib/weui.min.css">
        <link rel="stylesheet" href="css/jquery-weui.css">
        <link rel="stylesheet" href="css/font-awesome.min.css">
        <link rel="stylesheet" href="css/demos.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap.min.css">
        <link rel="stylesheet" href="/admin/ui/css/bootstrap-theme.min.css">
    </head>
    <style>
        .weui-input {
            width: 150px;
            text-align: right;
            border: solid 1px #fff !important;
        }

        .radio-inline { width: 30% !important; margin-left: 5px !important; }
    </style>
<body ontouchstart>
    <div class="top">
        <div class="user_top"><i>
                <?php
                if (intval($level) > 1) {
                    echo '<a href="manage.php">' . $userInfo['groupname'] . '</a>';
                } else {
                    echo $userInfo['groupname'];
                } ?>
            </i>
            <div class="user_top_conn"><img src="<?php echo $userInfo['headimgurl'] ?>"/>
                <p><?php echo $userInfo['truename'] ?></p>
                <?php if (intval($level) > 1) { ?>
                    <a class="user_link" href="member.php">返回用户</a>
                <?php } ?>
            </div>
        </div>
    </div>
    <!--工单详情开始-->
    <div class="main">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i>工单信息</div>
        <div class="weui-form-preview">
            <div class="weui-form-preview__bd">
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">工单号：</label>
                    <span class="weui-form-preview__value">
		<?php
        if (!empty($row['poster'])) {
            echo '<i class="fa fa-smile-o blue "></i>';
        }
        if (!empty($row['openid'])) {
            echo '<i class="fa fa-weixin green"></i>';
        }
        ?>
        <?php echo date("Ymd", $row['post_time']) . "-" . $row['id'] ?>
        </span>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">单位：</label>
                    <span class="weui-form-preview__value"><?php echo $row['school'] ?></span></div>
                <?php if (!empty($row['truename'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">联系人：</label>
                        <span class="weui-form-preview__value"><?php echo $row['truename'] ?></span></div>
                <?php } ?>
                <?php if (!empty($row['mobile'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">电话：</label>
                        <span class="weui-form-preview__value"><a href="tel:<?php echo $row['mobile'] ?>"><i class="fa fa-mobile"><?php echo $row['mobile'] ?></a></i></span>
                    </div>
                <?php } ?>
                <?php if (!empty($row['mobile'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">地址：</label>
                        <span class="weui-form-preview__value" id="daohang" data-orderid="<?php echo $row['id'] ?>"><i class="fa fa-map-marker"><?php echo $row['address'] ?></i></span>
                    </div>
                <?php } ?>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">服务类型：</label>
                    <span class="weui-form-preview__value"><i class="fa  fa-drivers-license-o red"></i> <?php echo getRepairMode($row['apply_device']) ?></span>
                </div>


                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">故障描述：</label>
                    <span class="weui-form-preview__value"><?php echo $row['content'] ?></span></div>

                <?php if (!empty($row['manageid'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">执行人：</label>
                        <span class="weui-form-preview__value">
			<?php
            if (!empty($row['manageid'])) {
                $m_str = $row['manageid'];
                $m_arr = explode(",", $m_str);
                foreach ($m_arr as $key => $val) {
                    echo ' <i class="fa  fa-user-o red"></i>      ' . getManage($val);
                }
            }
            ?>

        </span></div>
                <?php } ?>
                <?php if (!empty($row['begintime'])) { ?>
                    <div class="weui-form-preview__item">
                        <label class="weui-form-preview__label">任务时间：</label>
                        <span class="weui-form-preview__value"><i class="fa fa-play green"></i> <?php echo date("Y-m-d H:i:s", $row['begintime']) . "  
		<br/><i  class=' red fa  fa-stop'></i>     " . date("Y-m-d H:i:s", $row['endtime']) ?></span></div>
                <?php } ?>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label">故障图片</label>
                    <div class="weui-uploader">
                        <div class="weui-uploader__bd">
                            <ul class="weui-uploader__files" id="uploaderFiles">
                                <?php echo $pic_lists; ?>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="weui-form-preview__item">
                    <label class="weui-form-preview__label red">任务进度</label>
                    <span class="weui-form-preview__value">
        <ul>
          <?php
          $dosql->Execute("SELECT * FROM `#@__order_log` WHERE orderid='$orderid'  ORDER BY id asc");
          while ($row2 = $dosql->GetArray()) {
              if ($row2['latitude'] != "") {
                  ?>
                  <li><a href="openMap.php?orderid=<?php echo $orderid; ?>&logid=<?php echo $row2['id']; ?>"><i class="fa fa-check-circle"><?php echo $row2['op'] ?></i> <?php echo date("m-d H:i:s", $row2['op_time']) ?>
                          <i class="red fa fa-map-pin "></i></a></li>
              <?php } else {
                  ?>
                  <li><i class="fa fa-check-circle"><?php echo $row2['op'] ?></i> <?php echo date("m-d H:i:s", $row2['op_time']) ?></li>
                  <?php
              }
          }
          ?>
        </ul>
        </span></div>
                <div class="sub_btn"></div>
                <input type="hidden" name="manageid" id="manageid" value="<?php echo $uid; ?>">
                <input type="hidden" id="latitude" name="latitude">
                <input type="hidden" id="longitude" name="longitude">
                <input type="hidden" id="accuracy" name="accuracy">
                <input type="hidden" id="address" name="address">
                <input type="hidden" id="address_name" name="address_name" value="">
            </div>
        </div>
    </div>
    <!--工单详情结束-->
<?php if ($jindu2 < 5 && $jindu2 != 0) { ?>
    <div class="main">
        <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 派单：</div>
        <!--完修模块-->
        <form name="form" id="form" method="post" action="">
            <div class="weui-cells weui-cells_form">
                <div class="weui-cells__title">服务工程师：</div>
                <div class="weui-cells ">
                    <div id="gongchengshi" class="alert alert-success" role="alert">
                        公司本部：<br/>
                        <?php
                        $dosql->Execute("SELECT * FROM  `#@__user`  WHERE `level`=3   ORDER BY id asc", 8);
                        while ($row3 = $dosql->GetArray(8)) {
                            echo '<label class="checkbox-inline"><input  type="checkbox" name="manageid"  value="' . $row3['id'] . '" >' . $row3['truename'] . '</label>';
                        }
                        ?>
                    </div>

                    <div id="gongchengshi2" class="alert alert-warning" role="alert">
                        授权服务站：<br/>
                        <?php
                        $dosql->Execute("SELECT * FROM  `#@__user`    WHERE `level`=4  ORDER BY id asc", 9);
                        while ($row3 = $dosql->GetArray(9)) {
                            echo '<label class="checkbox-inline"><input  type="checkbox" name="manageid"  value="' . $row3['id'] . '" >' . $row3['truename'] . '</label>';
                        }
                        ?>
                    </div>

                    <input type="hidden" name="manageids" id="manageids" value=""/>
                </div>
                <div class="weui-cells__title"> 联系客户备注：</div>
                <div class="weui-cells ">
                    <div class="weui-cell">
                        <div class="weui-cell__bd">
                            <textarea class="form-control" name="content2" id="content2" placeholder="请输入文本"
                                      rows="3"></textarea>
                            <div class="weui-textarea-counter"><span>0</span>/200</div>
                        </div>
                    </div>
                </div>
            </div>
            <!--上传 开始-->

            <!--上传 结束-->
            <input type="hidden" name="action" id="action" value="add"/>

        </form>
        <!-- 完修模块-->
        <div class="sub_btn"><a href="javascript:;" class="weui-btn weui-btn_primary"
                                onclick="cfm_order();return false;">确认派单</a></div>
        <div class="clear"></div>
    </div>
<?php } ?>
    <div class="clear"></div>
    <div class="sub_btn"></div>
    <script src="lib/jquery-2.1.4.js"></script>
    <script src="lib/fastclick.js"></script>
    <script src="js/jquery-weui.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script>
        var checkids = []; //选择的工程师id
        $(function () {
            FastClick.attach(document.body);


            //选择工程师
            $("input[name='manageid']").change(function () {
                // 是否选择工程师
                checkids = [];
                ids = "";
                $("input[name='manageid']:checked").each(function (i) {
                    checkids[i] = $(this).val();
                });

                ids = checkids.join(",");
                console.log(ids);
                //重新给隐藏参数赋值
                $("#manageids").val(ids);
                if (checkids.length == 0 ) {
                    $.toast("至少选择一位工程师", "forbidden");
                    return false;
                }
            });

        });


        //提交表单
        function cfm_order() {


            if ($("#manageids").val() == "" ) {
                $.toast("至少选择一位工程师", "forbidden");
                return false;
            }


            $("#form").submit();

        }

        wx.config({
            debug: false,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'openAddress',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'
            ]
        });
        wx.ready(function () {
            //预览图片
            var apply_images = $("#uploaderFiles_apply").find("img");
            var imgPaths = [];
            apply_images.each(function () {
                imgPaths.push(this.src);
            });
            $("#uploaderFiles_apply").on("click", function () {
                current = imgPaths[0];
                wx.previewImage({
                    current: current,
                    urls: imgPaths
                });
            });


        })


    </script>
<?php
//工单提交处理

if (isset($action) and $action == 'add') {
    if (empty($manageids)) {
        echo '<script type="text/javascript">
	$.toast("请选择服务工程师", function() {
		});
	</script>';
        exit();
    }
    $content2 = htmlspecialchars($content2);
    $post_time = time();
    $post_time2 = date("Y-m-d H:i:s", time());


    //修改任务的 执行人
    $dosql->ExecNoneQuery("update  `#@__order` set  jindu='3',manageid='$manageids',remark='$content2',remark_time='$post_time' where  id='$orderid' ");
    //插入更新的状态

    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid,remark) values ('$orderid','已经联系客户','$post_time','2','$manageids','$content2')");
    $dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu,manageid,remark) values ('$orderid','已经派单','$post_time','3','$manageids','$content2')");

    $orderidname = date('Ymd', time()) . "-" . $orderid;

    //派单模式工程师是 指定的伙伴
    $mode_user = array();
    $mode_user_arr = explode(",",$manageids);
    if(is_array($mode_user_arr)){
        foreach ($mode_user_arr as $u_key=>$u_val){
            $mode_user[]=getManageOpenidFromUid($u_val);
        }
    }


    $fee = "";
    //调取任务奖励
    if ($apply_device > 0) {
        $fee_arr = $dosql->GetOne("SELECT * FROM `#@__task` WHERE id='$apply_device'");
        if (is_array($fee_arr) && isset($fee_arr['id'])) {
            $fee = $fee_arr['value'];
        }
    }


    //给终端客户发送派单信息
//    $send_tpl_message_remark="系统已经发送给指定的工程师了，请等待工程师接单吧。";
    $first_word="📢 您好,用户报修系统自动下发拍单任务。请处理";
    $remark_word="👉请点击处理，如有特殊情况，请转单给其他工程师。服务热线:". $cfg_hotline."👈";

    //处理工单
    foreach ($mode_user as $key => $val) {
        //获取工程师 openid
        $openid_str = $val;
        //封装为json格式的数据
        $repairname = getRepairMode($apply_device);
        $repairname = $repairname . "  奖励  " . $fee;
        $send_body['touser'] = $openid_str;
        $send_body['template_id'] = $cfg_neworder;
        $send_body['url'] = $cfg_weburl . 'wx/morderDetail.php?orderid=' . $orderid;
        $send_body['data']['first']['value'] = $first_word;
        $send_body['data']['first']['color'] = "#FF0000";
        $send_body['data']['keyword1']['value'] = $orderidname;
        $send_body['data']['keyword1']['color'] = "#173177";
        $send_body['data']['keyword2']['value'] = $repairname;
        $send_body['data']['keyword2']['color'] = "#FF0000";
        $send_body['data']['keyword3']['value'] = $post_time2;
        //$send_body['data']['keyword3']['color'] = "#FF0000";
        $send_body['data']['keyword4']['value'] = "💗" . $school . "-" . $truename;
        $send_body['data']['keyword4']['color'] = "#0e48cb";
        $send_body['data']['keyword5']['value'] = "⛳" . $address;
        $send_body['data']['keyword5']['color'] = "#0e48cb";
        $send_body['data']['remark']['value'] = $remark_word;
        $send_body['data']['remark']['color'] = "#FF0000";

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $g_AccessToken;
        $res = $jssdk->https_curl_json($url, $send_body, 'json');
        //var_dump($res);
        //$jssdk->return_json_body(['code'=>0,'msg'=>'添加成功']);


    }



    echo '<script type="text/javascript">
	$.toast("派单成功", function() {
		 window.location.href="morderDetail.php?orderid=' . $orderid . '";
		});
	</script>';
    exit();

}

?>
<?php require_once('footer.php'); ?>